package com.wuyou.mid;

/**
 * 904. 水果成篮
 */
public class TotalFruit {


    public static void main(String[] args) {
        int[] fruits = {1, 0, 2, 3, 4};
        System.out.println(solution_1(fruits));
    }

    public static int solution_1(int[] fruits) {
        if (fruits.length == 0) return 0;
        int res = 0;
        Integer f1 = fruits[0], f2 = null, num1 = 1, num2 = 0, f1Index = 0, f2Index = 0;
        for (int i = 1; i < fruits.length; i++) {
            if (f1 == fruits[i]) {
                num1++;
                f1Index = i;
            } else if (f2 == null) {
                f2 = fruits[i];
                num2 = 1;
                f2Index = i;
                continue;
            } else if (f2 == fruits[i]) {
                num2++;
                f2Index = i;
                continue;
            } else {
                res = Math.max(res, num1 + num2);
                if (f1Index - f2Index < 0) {
                    f1 = fruits[i];
                    num1 = 1;
                    num2 = Math.abs(f1Index - f2Index);
                    f1Index = i;
                } else {
                    f2 = fruits[i];
                    num2 = 1;
                    num1 = f1Index - f2Index;
                    f2Index = i;
                }
            }
        }
        return Math.max(res, num1 + num2);
    }
}
